package com.cus.tom.transfer.ac;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;

import androidx.annotation.Nullable;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.R;
import com.cus.tom.transfer.adapter.ChooseAdapter;
import com.cus.tom.transfer.bean.Const;
import com.cus.tom.transfer.bean.FileType;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.databinding.ActivityChooseBinding;
import com.cus.tom.transfer.frag.AppFragment;
import com.cus.tom.transfer.frag.BaseDialogFragment;
import com.cus.tom.transfer.frag.ImgFragment;
import com.cus.tom.transfer.frag.InfoFragment;
import com.cus.tom.transfer.frag.LoadingDlg;
import com.cus.tom.transfer.frag.TipDlg;
import com.cus.tom.transfer.utils.ComUtility;
import com.cus.tom.transfer.utils.Read;
import com.cus.tom.transfer.utils.ToastUtil;
import com.cus.tom.transfer.utils.Utils;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ChooseAct extends BaseAct {
    ActivityChooseBinding binding;
    ChooseAdapter adapter;
    InfoFragment fragment;
    long[] selectSize = new long[7];
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ImgFragment.img.clear();
            ImgFragment.audio.clear();
            ImgFragment.video.clear();
            AppFragment.set.clear();
            finish();
        }
    };

    Runnable loadRunnable = new Runnable() {
        @Override
        public void run() {
            if (fragment == null || fragment.getActivity() == null) {
                h.postDelayed(this, 500);
                return;
            }
            fragment.loadData();
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityChooseBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.back.setOnClickListener(v -> finish());

        IntentFilter filter = new IntentFilter(Const.EXIT_RESULT);
        registerReceiver(receiver, filter);

        adapter = new ChooseAdapter(binding.linear, this);
        fragment = new InfoFragment(0, 0);
        replaceFragment(R.id.frame, fragment);

        binding.send.setOnClickListener(v -> {
            if (!XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION)) {
                TipDlg dlg = new TipDlg().setMsg("为了和新手机建立通信，需要您授予定位权限");
                dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                    @Override
                    public void onDismiss(boolean isOk, Object value) {
                        if (isOk) {
                            Read.toSetting(ChooseAct.this, new Runnable() {
                                @Override
                                public void run() {
                                    if (getSelectSize() == 0) {
                                        ToastUtil.showShortToast(App.getApp(), "选择要发送的文件");
                                        return;
                                    }
                                    prepare();
                                }
                            }, false, Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION);
                        }
                    }
                });
                dlg.show(getSupportFragmentManager(), "");
                return;
            }
            if (getSelectSize() == 0) {
                ToastUtil.showShortToast(this, "选择要发送的文件");
                return;
            }
            prepare();
        });

        Read.toRead(this, "需要读取存储文件权限以便获取照片和视频", new Runnable() {
            @Override
            public void run() {
                if (XXPermissions.isGranted(ChooseAct.this, Permission.MANAGE_EXTERNAL_STORAGE)) {
                    loadImage();
                    loadVideo();
                    loadAudio();
                    loadApps();
                }
                h.removeCallbacks(loadRunnable);
                h.post(loadRunnable);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        ImgFragment.video.clear();
        ImgFragment.audio.clear();
        ImgFragment.img.clear();
        AppFragment.set.clear();
    }

    long totalImageNum, totalImageSize;

    private void loadImage() {
        totalImageNum = 0;
        totalImageSize = 0;
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                int page = 0;
                Read read = new Read();
                while (true) {
                    List<MediaData> list = read.loadImageData(App.getApp(), page);
                    if (list.isEmpty()) {
                        break;
                    }
                    ++page;
                    if (list.size() == 1 && !list.get(0).isValid) {
                        ;
                    } else {
                        updateImageInfo(list);
                    }
                }
                if (totalImageNum == 0) {
                    updateImageInfo(Collections.emptyList());
                }
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    private void updateImageInfo(List<MediaData> list) {
        h.post(() -> {
            totalImageNum += list.size();
            for (MediaData item : list) {
                totalImageSize += item.getSize();
            }
            adapter.notifyItemChanged(0, totalImageNum, 0);
        });
    }

    long totalVideoNum, totalVideoSize;

    private void loadVideo() {
        totalVideoNum = 0;
        totalVideoSize = 0;
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                int page = 0;
                Read read = new Read();
                while (true) {
                    List<MediaData> list = read.loadVideo(App.getApp(), page);
                    if (list.isEmpty()) {
                        break;
                    }
                    ++page;
                    if (list.size() == 1 && !list.get(0).isValid) {
                        ;
                    } else {
                        updateVideoInfo(list);
                    }
                }
                if (totalVideoNum == 0) {
                    updateVideoInfo(Collections.emptyList());
                }
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    private void updateVideoInfo(List<MediaData> list) {
        h.post(() -> {
            totalVideoNum += list.size();
            for (MediaData item : list) {
                totalVideoSize += item.getSize();
            }
            adapter.notifyItemChanged(1, totalVideoNum, 0);
        });
    }

    long totalAudioNum, totalAudioSize;

    private void loadAudio() {
        totalAudioNum = 0;
        totalAudioSize = 0;
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                int page = 0;
                Read read = new Read();
                while (true) {
                    List<MediaData> list = read.loadAudio(App.getApp(), page);
                    if (list.isEmpty()) {
                        break;
                    }
                    ++page;
                    if (list.size() == 1 && !list.get(0).isValid) {
                        ;
                    } else {
                        updateAudioInfo(list);
                    }
                }
                if (totalAudioNum == 0) {
                    updateAudioInfo(Collections.emptyList());
                }
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    private void updateAudioInfo(List<MediaData> list) {
        h.post(() -> {
            totalAudioNum += list.size();
            for (MediaData item : list) {
                totalAudioSize += item.getSize();
            }
            adapter.notifyItemChanged(2, totalAudioNum, 0);
        });
    }

    long totalAppNum;

    private void loadApps() {
        List allApps = new Read().loadApps();
        totalAppNum = allApps.size();
        adapter.notifyItemChanged(3, allApps.size(), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3 && resultCode == RESULT_OK) {
            long num = data.getLongExtra("num", 0);
            long size = data.getLongExtra("size", 0);
            adapter.notifyItemChanged(3, totalAppNum, size, num);
            selectSize[3] = size;
        } else if (requestCode == 0 && resultCode == RESULT_OK) {
            long num = data.getIntExtra("num", 0);
            long size = data.getLongExtra("size", 0);
            adapter.notifyItemChanged(0, totalImageNum, size, num);
            selectSize[0] = size;
        } else if (requestCode == 1 && resultCode == RESULT_OK) {
            long num = data.getIntExtra("num", 0);
            long size = data.getLongExtra("size", 0);
            adapter.notifyItemChanged(1, totalVideoNum, size, num);
            selectSize[1] = size;
        } else if (requestCode == 2 && resultCode == RESULT_OK) {
            long num = data.getIntExtra("num", 0);
            long size = data.getLongExtra("size", 0);
            adapter.notifyItemChanged(2, totalAudioNum, size, num);
            selectSize[2] = size;
        }
        if (resultCode == RESULT_OK) {
            if (select.contains(requestCode)) {
                updateSelect(requestCode, true);
            } else {
                long size = data.getLongExtra("size", 0);
                if (size > 0) {
                    adapter.checkTypeFile(requestCode);
                }
            }
        }
    }

    public void setSize(long size, int index) {
        selectSize[index + 4] = size;
    }

    HashSet<Integer> select = new HashSet<>();

    public void updateSelect(int i, boolean bo) {
        if (bo) {
            select.add(i);
        } else {
            select.remove(i);
        }
        long size = getSelectSize();
        binding.size.setText(Utils.formatSize(size));
        binding.time.setText(String.format("%.2f", size / 800000f) + "s");
    }

    private long getSelectSize() {
        long total = 0;
        for (int j : select) {
            total += selectSize[j];
        }
        return total;
    }

    private void prepare() {
        LoadingDlg dlg = new LoadingDlg();
        dlg.show(getSupportFragmentManager(), "");
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                ArrayList<String> list = doPrepare();
                h.post(() -> {
                    dlg.dismiss();
                    Intent i = new Intent(ChooseAct.this, CodeAct.class);
                    i.putStringArrayListExtra("files", list);
                    i.putExtra("set", select);
                    startActivity(i);
                });
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    private ArrayList<String> doPrepare() {
        try {
            File f = new File(Environment.getExternalStorageDirectory(), App.getApp().getPackageName());
            if (f.exists()) {
                Utils.deleteFile(f);
            }
            if (select.contains(FileType.APP.getCode())) {
                return copyApp(AppFragment.set);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return new ArrayList();
    }

    private ArrayList<String> copyApp(Set<String> set) {
        File f = new File(Environment.getExternalStorageDirectory(), App.getApp().getPackageName());
        f.mkdirs();
        ArrayList<String> list = new ArrayList<>();
        for (String name : set) {
            String str = ComUtility.android_command("pm path " + name);
            str = str.substring(str.indexOf("/"));
            StringBuffer sb = new StringBuffer();
            File tmp = new File(f, name + ".apk");
            sb.append("cp ").append(str).append(" ").append(tmp.getAbsolutePath());
            str = ComUtility.android_command(sb.toString());
            list.add(tmp.getAbsolutePath());
            System.currentTimeMillis();
        }
        return list;
    }

    public void askPermission(int i) {
        if (i < 4) {
            Read.toSetting(this, new Runnable() {
                @Override
                public void run() {
                    Intent in = new Intent(ChooseAct.this, ListAct.class);
                    in.putExtra("index", i);
                    startActivityForResult(in, i);
                }
            }, false, Permission.MANAGE_EXTERNAL_STORAGE);
        } else {
            fragment.askPermission(i - 4);
        }
    }
}
